#!/usr/bin/perl -w
#
# Show a person record in cleaned format

use strict;

use Counter;
#use FileTable;
use Validate::Persons;
use Validate::Machines;
use Validate::Friends;
use Fcntl;

use vars qw{
    $file $preen $filter $key
    $persons $users $pers $user $field
    };

if ($ENV{COUNTER_ROOT}) {
    $file = $ENV{COUNTER_ROOT} . "/db/persons";
} else {
    $file = "persons";
}

while (defined($ARGV[0]) && $ARGV[0] =~ /^-/) {
    my $opt = shift;
    if ($opt eq "-w") {
	$preen = 1;
    } elsif ($opt eq "-f") {
	$file = shift;
    } elsif ($opt eq "-filter") {
	$filter = 1;
    }
}
if (! -f "$file.conf") {
    $file = "db/" . $file;
}
if (!$ARGV[0] && !$filter) {
    die "Usage: $0 [-w] [-f file] recno...\n" .
	"       $0 -filter < numfile\n";
}

if ($preen) {
    $persons = FileTable::open($file, O_RDWR);
} else {
    $persons = FileTable::open($file);
}
if ($file =~ /persons$/) {
    my $usersfile = $file;
    $usersfile =~ s/persons$/users/;
    $users = FileTable::open($usersfile);
}

if ($filter) {
    while (<>) {
	if (/^(\d+)/) {
	    $key = $1;
	    print "** Key $key\n";
	    eval "showclean($key)"; # catch die()s....
	}
    }
} else {
    for $key (@ARGV) {
	showclean($key);
    }
}

sub showclean {
    my $clean = shift;

    print "============= Record $key ============\n";
    if ($users) {
	$user = $users->get($key);
	$$user{email} = "--nothing--" if !$$user{email};
	printf "** %-9s: %s\n", "Replyto", $$user{email};
    }
    $pers = $persons->get($key);
    if (!$pers) {
	print "No person entry for $key\n";
	return;
    }
# Preen: Invoke implicitly the cleaning routines
    if ($preen) {
	$pers->clean;
    }
    $clean = $persons->getclean($key);
    if (!$clean) {
	die "Error for $key in $file: Entry exists but no clean\n";
    }
    
    for $field ($clean->fields) {
	if (!defined($$clean{$field})) {
	    warn "Strange: field in clean->fields but undefined\n";
	}
	if (!defined($$pers{$field})) {
	    printf "%-12s: %s []\n", $field, $$clean{$field};
	} elsif ($$pers{$field} ne $$clean{$field}) {
	    printf "%-12s: %s (%s)\n", $field, $$clean{$field}, $$pers{$field};
	} else {
	    printf "%-12s: %s\n", $field,  $$pers{$field};
	}
    }
    if ($user) {
	my @emails;
	my $email;
	print "Associated emails:\n";
	@emails = $user->emails();
	for $email (@emails) {
	    printf "%-5s %-5s %s\n",
	    $$email{state}, $$email{usage}, $email->key();
	}
    }
}

	
